package com.zhanglinwei.openApiClient.segment;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.zhanglinwei.common.constants.StringPoolConstant.COMMA_SPACE;

@Getter
@Setter
public class OrderBySegment implements SQLSegment {

    private final List<OrderByItem> orderBySegmentList = new ArrayList<>();

    @Override
    public boolean isEmpty() {
        return CollectionUtils.isEmpty(orderBySegmentList);
    }

    @Override
    public void add(SQLSegment... sqlSegments) {
        if (ArrayUtils.isNotEmpty(sqlSegments)) {
            Arrays.stream(sqlSegments)
                    .filter(item -> item instanceof OrderByItem)
                    .forEach(item -> orderBySegmentList.add((OrderByItem) item));
        }
    }

    @Override
    public String sqlSegment() {
        return SQLKeyword.ORDER_BY.sqlSegment() + " " + orderBySegmentList.stream().map(OrderByItem::sqlSegment).collect(Collectors.joining(COMMA_SPACE));
    }

    public static class OrderByItem implements SQLSegment {
        private final String column;
        private final boolean asc;

        public OrderByItem(String column, boolean asc) {
            this.column = column;
            this.asc = asc;
        }

        @Override
        public String sqlSegment() {
            return column + " " + (asc ? SQLKeyword.ASC.sqlSegment() : SQLKeyword.DESC.sqlSegment());
        }
    }

}
